package Code

import (
	v12 "Yoj/internal/controller/YJudger"
	"Yoj/internal/dao"
	"Yoj/internal/model/do"

	"context"
	"github.com/gogf/gf/v2/os/glog"
	"github.com/gogf/gf/v2/os/gtime"

	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"

	"Yoj/api/Code/TextSubmit"
)

// 写入数据库;
func TextCodeWriteToDatabase(ctx context.Context, req *TextSubmit.CodeTextSubmitReq, content *string) (int64, error) {
	result, err := dao.Submit.Ctx(ctx).Insert(do.Submit{
		SubmitUser: req.Qid,
		SubmitAt:   gtime.Now(),
		Code:       content,
		ProblemId:  req.Problem,
	})
	if err != nil {
		glog.Error(ctx, err)
		return 0, gerror.NewCode(gcode.CodeInternalError, "数据库写入失败")
	}
	id, err := result.LastInsertId()
	if err != nil {
		glog.Error(ctx, err)
		return 0, gerror.NewCode(gcode.CodeInternalError, "数据库写入失败")
	}
	return id, nil
}

func (c *ControllerTextSubmit) CodeTextSubmit(ctx context.Context, req *TextSubmit.CodeTextSubmitReq) (res *TextSubmit.CodeTextSubmitRes, err error) {
	// 校验参数;
	if v12.CheckLanguage(req.Language) == false {
		return nil, gerror.NewCode(gcode.CodeInvalidParameter, "不支持的语言")
	}
	if req.Name != ctx.Value("username").(string) {
		return nil, gerror.NewCode(gcode.CodeInvalidParameter, "用户名校验失败")
	}
	if req.Qid != ctx.Value("qid").(string) {
		return nil, gerror.NewCode(gcode.CodeInvalidParameter, "Qid校验失败")
	}

	// 写入数据库;
	var submitId int64
	if submitId, err = TextCodeWriteToDatabase(ctx, req, &req.Code); err != nil {
		return nil, err
	}

	// TODO: 通知评测机;

	// 返回提交id;
	res = &TextSubmit.CodeTextSubmitRes{
		Submitid: submitId,
	}

	return nil, gerror.NewCode(gcode.CodeNotImplemented)
}
